package com.ctfo.ulcp.exp.utils;

import groovy.text.SimpleTemplateEngine;
import groovy.text.Template;
import groovy.text.TemplateEngine;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public record TableInfo(String name, String comment, List<ColumnDefinition> columns, TableType tableType) {

    public String genSummary() throws IOException, ClassNotFoundException {
        /*
         * ${name ?: ''} 和 ${item?.code ?: ''} 这样的表达式使用了Groovy的空合并操作符（safe navigation operator ?.）和Elvis操作符（?:）。
         * 如果表达式左边的对象为null，则返回右边的值，这里是一个空字符串。
         */

        String template = """
                表名: ${table.name} - ${table.comment?: ''}
                字段: <% for(column in table.columns) { %>
                ${column.name}(${column.type}) - ${column.comment ?: ''},示例数据:${column.sample()} <% } %>
                """;

        Map<String, Object> binding = new HashMap<>();
        binding.put("table", this);
        TemplateEngine engine = new SimpleTemplateEngine();
        Template groovyTemplate = engine.createTemplate(template);
        Writer writer = new StringWriter();
        groovyTemplate.make(binding).writeTo(writer);
        return writer.toString();

    }


}
